package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmChannelDto;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.thread.AdminThreadLocalUtil;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.WmChannelService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
@Slf4j
public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel> implements WmChannelService {

    /**
     * 查询所有频道
     *
     * @return
     */
    @Override
    public ResponseResult findAll() {
        return ResponseResult.okResult(list());
    }

    /**
     * 保存频道
     *
     * @param wmChannel
     * @return
     */
    @Override
    public ResponseResult saveChannel(WmChannel wmChannel) {
        // 参数校验
        if (StringUtils.isBlank(wmChannel.getName()) || StringUtils.isBlank(wmChannel.getDescription())) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if (wmChannel.getOrd() == null) {
            wmChannel.setOrd(0);
        }
        if (wmChannel.getStatus() == null) {
            wmChannel.setStatus(true);
        }
        // 如果数据库中存在，则新增失败
        WmChannel dbChannel = getOne(Wrappers.<WmChannel>lambdaQuery()
                .eq(WmChannel::getName, wmChannel.getName()));
        if (dbChannel != null) {
            return ResponseResult.errorResult(201, "频道已存在，新增失败");
        }
        // 补全参数
        wmChannel.setIsDefault(true);
        wmChannel.setCreatedTime(new Date());
        // 保存数据
        save(wmChannel);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查看频道列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult list(WmChannelDto dto) {
        // 检查参数
        dto.checkParam();
        // 查询是否登录
        AdUser adUser = AdminThreadLocalUtil.getUser();
        if (adUser == null) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 分页查询
        IPage<WmChannel> page = new Page<>(dto.getPage(), dto.getSize());
        page = page(page, Wrappers.<WmChannel>lambdaQuery()
                .like(StringUtils.isNotEmpty(dto.getName()), WmChannel::getName, dto.getName())
                .orderByDesc(WmChannel::getCreatedTime));
        // 封装对象，并赋值
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(),
                (int) page.getTotal());
        responseResult.setData(page.getRecords());
        // 返回结果
        return responseResult;
    }

    @Autowired
    private WmNewsMapper wmNewsMapper;

    /**
     * 修改频道
     *
     * @param wmChannel
     * @return
     */
    @Override
    public ResponseResult updateChannel(WmChannel wmChannel) {
        // 检查参数
        if (wmChannel == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 如果数据库中存在，则修改失败
        WmChannel dbChannel = getOne(Wrappers.<WmChannel>lambdaQuery()
                .eq(WmChannel::getName, wmChannel.getName()));
        if (dbChannel != null) {
            return ResponseResult.errorResult(201, "频道已存在，修改失败");
        }
        // 如果频道被引用，不能禁用
        List<WmNews> wmNewsList = wmNewsMapper.selectList(Wrappers.<WmNews>lambdaQuery()
                .eq(WmNews::getChannelId, wmChannel.getId()));
        if (wmNewsList != null && wmNewsList.size() > 0 && !wmChannel.getStatus()) {
            return ResponseResult.errorResult(201,"频道被引用，不能禁用");
        }
        // 修改
        updateById(wmChannel);
        // 返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 删除频道
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult deleteChannel(Integer id) {
        // 参数校验
        if (id == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 查询频道
        WmChannel wmChannel = getById(id);
        // 如果频道已启用，无法删除
        if (wmChannel.getStatus()) {
            return ResponseResult.errorResult(201, "频道已启用，无法删除");
        }
        // 执行方法
        removeById(id);
        // 返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}